package com.weir.resources.permissions.service.impl;

import com.weir.resources.permissions.entity.PermMenu;
import com.weir.resources.permissions.mapper.PermMenuMapper;
import com.weir.resources.permissions.service.IPermMenuService;
import com.weir.resources.permissions.vo.MenuVo;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 菜单 服务实现类
 * </p>
 *
 * @author weir
 * @since 2018-12-24
 */
@Service
public class PermMenuServiceImpl extends ServiceImpl<PermMenuMapper, PermMenu> implements IPermMenuService {
	@Override
	public List<MenuVo> getTrees(Integer id,Integer userId) {
		List<PermMenu> modules = null;
		if (id==null) {
			modules = getModule(new QueryWrapper<PermMenu>().isNull("pid").eq("ur.user_id", userId).groupBy("m.id"));
//			modules = getModule(new EntityWrapper<PermMenu>().where("pid is null").where("ur.userid={0}", userid).groupBy("m.id"));
		}else {
			modules = getModule(new QueryWrapper<PermMenu>().eq("m.pid",id).eq("ur.user_id", userId).eq("m.step", 1).groupBy("m.id"));
		}
		List<MenuVo> menus = new ArrayList<MenuVo>();
		MenuVo m = null;
		for (PermMenu module : modules) {
			m = new MenuVo();
			BeanUtils.copyProperties(module, m);
			m.setId(module.getId().toString());
			int mun = count(new QueryWrapper<PermMenu>().eq("pid",module.getId()).eq("step", 1));
			
			Map<String, Object> attributes = new HashMap<String, Object>();
			attributes.put("url", module.getUrl());
			m.setAttributes(attributes);
			if (mun>0) {
				m.setState("closed");
			}else {
				m.setState("open");
			}
			menus.add(m);
		}
		return menus;
	}
	
	@Override
	public List<MenuVo> listTree() {
		List<PermMenu> modules = list();
		List<MenuVo> menus = new ArrayList<MenuVo>();
		MenuVo m = null;
		for (PermMenu tmenu : modules) {
			m = new MenuVo();
			m.setId(tmenu.getId().toString());
			m.setName(tmenu.getText());
			m.setText(tmenu.getText());
			m.setCode(tmenu.getCode());
			m.setUrl(tmenu.getUrl());
			PermMenu t = getById(tmenu.getPid());
			if (t!=null) {
				m.setPid(t.getId().toString());
				m.setPname(t.getText());
			}
			menus.add(m);
		}
		return menus;
	}
	@Override
	@Transactional
	public void delete(Integer id) {
		getList(id);
		removeById(id);
	}
	@Transactional
	protected void getList(Integer id){
		List<PermMenu> modules = list(new QueryWrapper<PermMenu>().eq("pid",id));
		for (PermMenu tmenu : modules) {
			removeById(tmenu.getId());
			getList(tmenu.getId());
		}
	}
	
	@Override
	public List<PermMenu> getModule(Wrapper<PermMenu> wrapper) {
		return baseMapper.getModule(wrapper);
	}
}
